import { showToast,requestPayment } from '../../utils/asyncWx'
import {request} from '../../request/index';
Page({
  data: {
    address:{},
    cart:[],
    totalPrice:0,
    totalNum:0
  },
  onShow() {
    //获取缓存中的收货地址数据
    let address = wx.getStorageSync('address');
    address.all = `${address.cityName}${address.countyName}${address.detailInfo}`;
    //获取缓存中的购物车数据
    let cart = wx.getStorageSync('cart') || [];
    //过滤购物车数组，只要选中的数据
    cart = cart.filter(v=>v.isSelected);
     //计算总价格
     let totalPrice = 0;
     let totalNum = 0;
     cart.forEach(item => {
      totalPrice += item.goods_price * item.num;
      totalNum += item.num;
     })
     this.setData({
       cart,
       totalPrice,
       totalNum,
       address
     })
   },
   //结算
    async handlePay() {
      try {
        //判断缓存中有没有token
        const token = wx.getStorageSync('token');
        console.log(token)
        if(!token) {
         wx.switchTab({
           url: '/pages/auth/index',
         })
          return;
        };
        //获取到token
        //创建订单
        //1准备请求头参数
        const header = {Authorization:token};
        //请求体参数
        const order_price = this.data.totalPrice;
        const consignee_addr = this.data.address.all;
        const cart = this.data.cart;
        let goods = [];
        cart.forEach(v => goods.push({
          goods_id: v.goods_id,
          goods_number: v.num,
          goods_price: v.goods_price
        }));
        const prderParams = {order_price,consignee_addr,cart};
        //4 发送请求 创建订单 获取订单编号
        let {order_number} = await request({url:'/my/orders/create',method:'POST',data:prderParams,header})
        //5 发送预支付
        const {pay} = await request({url:"/my/orders/req_unifiedorder",method:'POST',header,data:{order_number}});
        //发起微信支付
        requestPayment(pay);
        //查询后台订单状态
        const res = await request({url:'/my/orders/chkOrder',method:'POST',header,data:{order_number}});
        //手动删除缓存中，已经支付了的商品
        let newCart = wx.getStorageSync('cart');
        newCart = newCart.filter(v => !v.isSelected);
        wx.setStorageSync('cart', newCart);

        await showToast('支付成功');
      } catch (error) {
        console.log(error);
        await showToast('支付失败');
      }
   }

  })

